<template>
    <div class="lyrics-container">
        <n-scrollbar style="max-height: 510px;">
            <div v-for="(line, index) in parsedLyrics" :key="index"
                :class="['lyric-line', { 'active': currentLineIndex === index }]" v-if="parsedLyrics.length > 0">
                {{ line.text }}
            </div>
            <n-empty v-else description="暂无歌词"></n-empty>
        </n-scrollbar>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { musicStore } from '@/store/musicStore';
import { ElMessage } from 'element-plus';

const store = musicStore();
const parsedLyrics = ref<Array<{ time: number, text: string }>>([]);
const currentLineIndex = ref(-1);

// 解析歌词
const parseLyrics = (lrcText: string) => {
    const lines = lrcText.split('\n');
    const lyrics = [];

    for (const line of lines) {
        const timeMatches = line.match(/\[(\d+):(\d+)\.(\d+)\]/g);
        if (!timeMatches) continue;

        const text = line.replace(/\[.*?\]/g, '').trim();

        for (const timeTag of timeMatches) {
            const timeMatch = timeTag.match(/\[(\d+):(\d+)\.(\d+)\]/);
            if (!timeMatch) continue;

            const minutes = parseInt(timeMatch[1]);
            const seconds = parseInt(timeMatch[2]);
            const milliseconds = parseInt(timeMatch[3]);

            const time = minutes * 60 * 1000 + seconds * 1000 + milliseconds * 10;

            lyrics.push({
                time,
                text
            });
        }
    }

    lyrics.sort((a, b) => a.time - b.time);

    return lyrics;
};

// 监听歌词变化
watch(() => store.lyricContent, (newLyrics) => {
    if (newLyrics) {
        parsedLyrics.value = parseLyrics(newLyrics);
    }
});

// 监听播放时间变化
watch(() => store.currentMusic.currentTime, (currentTime) => {
    if (!parsedLyrics.value.length) return;

    // 将当前时间转换为毫秒
    const currentTimeMs = currentTime * 1000;

    // 找到当前应该显示的歌词行
    let activeIndex = -1;
    for (let i = 0; i < parsedLyrics.value.length; i++) {
        if (parsedLyrics.value[i].time <= currentTimeMs) {
            activeIndex = i;
        } else {
            break;
        }
    }

    currentLineIndex.value = activeIndex;

    // 滚动到当前歌词           这个还没生效，后期优化
    if (activeIndex >= 0) {
        const container = document.querySelector('.n-scrollbar') as HTMLElement; // 直接操作 n-scrollbar
        const activeLine = document.querySelector(`.lyric-line:nth-child(${activeIndex + 1})`) as HTMLElement;

        if (container && activeLine) {
            // 动态滚动逻辑
            const containerRect = container.getBoundingClientRect();
            const activeLineRect = activeLine.getBoundingClientRect();

            // 判断当前歌词是否在可视范围内
            const isOutOfView =
                activeLineRect.bottom < containerRect.top || activeLineRect.top > containerRect.bottom;

            if (isOutOfView) {
                // 强制滚动到当前歌词位置
                container.scrollTo({
                    top: activeLine.offsetTop - container.clientHeight / 2 + activeLine.clientHeight / 2,
                    behavior: 'smooth',
                });
            }
        }
    }
});
</script>

<style scoped>
.lyrics-container {
    height: 89vh;
    overflow-y: auto;
    text-align: center;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.lyric-line {
    margin: 10px 0;
    padding: 8px 16px;
    font-size: 18px;
    color: #666;
    transition: all 0.3s ease;
}

.lyric-line.active {
    font-size: 22px;
    color: #333;
    position: relative;
    padding-bottom: 5px;
}

.lyric-line.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 3px;
    background: #409eff;
    border-radius: 3px;
}
</style>